package com.bw.paper.mvp.presenter;

import com.bw.paper.entity.UserEntity;
import com.bw.paper.mvp.base.model.BaseEntity;
import com.bw.paper.mvp.base.presenter.BasePresenter;
import com.bw.paper.mvp.contact.LoginContract;
import com.bw.paper.mvp.model.HttpCode;
import com.bw.paper.utils.ToastUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class LoginPresenter extends BasePresenter<LoginContract.LoginModel, LoginContract.LoginView> {

    @Inject
    public LoginPresenter(LoginContract.LoginModel mModel, LoginContract.LoginView mView) {
        super(mModel, mView);
    }


    //声明对应请求方法
    //phone->当前用户登录的手机号
    //pwd->用户密码
    public void requestLogin(long phone,String pwd,int code) {
        if (pwd.isEmpty()) {
            ToastUtils.showMsg("当前密码为空");
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("pwd", pwd);
        map.put("code", code);
        mModel.request(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    public void requestUpDataUser(UserEntity userEntity) {
        Map<String,Object> map=new HashMap<>();
        map.put("user_id",userEntity.getUser_id());
        map.put("user_img",userEntity.getUser_img());
        map.put("user_integral",userEntity.getUser_integral());
        map.put("user_name",userEntity.getUser_name());
        map.put("user_phone",userEntity.getUser_phone());
        map.put("user_pwd",userEntity.getUser_pwd());
        map.put("user_sex",userEntity.getUser_sex());
        map.put("code",HttpCode.UPDATEUSERCODE);
        mModel.request(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    public void RequestUpload(String path){
        Map<String, Object> map = new HashMap<>();
        File file = new File(path);
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.addFormDataPart("file","hfgc"+System.currentTimeMillis()+".jpg",body);
        List<MultipartBody.Part> list = builder.build().parts();
        map.put("list",list);
        map.put("code", HttpCode.UPLOADIMGCODE);
        mModel.request(map).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(this);
    }

    @Override
    public void onNext(@NonNull BaseEntity baseEntity) {
        mView.refreshView(baseEntity);
    }
}
